package com.example.tianling.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.tianling.common.params.PublishLearnArticleDo;
import com.example.tianling.common.params.PublishTrainArticleDo;
import com.example.tianling.common.utils.Check;
import com.example.tianling.common.utils.MinioUtils;
import com.example.tianling.common.vo.TrainArticleVo;
import com.example.tianling.common.vo.article;
import com.example.tianling.common.vo.articleCommonVo;
import com.example.tianling.dao.*;
import com.example.tianling.entity.*;
import com.example.tianling.entity.RoomEntity;
import com.example.tianling.service.ForumService;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.example.tianling.common.utils.ImageUtils.compress;
import static com.example.tianling.common.utils.toImg.*;

@Service
public class ForumServiceImpl
        extends ServiceImpl<ArticleMapper, ArticleEntity>
        implements ForumService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private RoomMapper reserveRoomMapper;
    @Autowired
    private LikeMapper likeMapper;
    @Autowired
    private SaveMapper saveMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MinioUtils minioUtils;
//加载刷新论坛页面
    public boolean is_follow_like_save(String user_id,String other_id,String action){
        Long code;
        if (action == "like"){
            QueryWrapper<LikeEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("article_id",other_id).eq("user_id",user_id);
            code = likeMapper.selectCount(queryWrapper);
        }
        else {
            QueryWrapper<SaveEntity> queryWrapper = new QueryWrapper<>();
            System.out.println("other_id");
            System.out.println(other_id);
            System.out.println(user_id);
            queryWrapper.eq("article_id",other_id).eq("user_id",user_id);
            code = saveMapper.selectCount(queryWrapper);

            System.out.println("code");
            System.out.println(code);
        }
        return code != 0;
    }
    public IPage<article> load(int pageNum,int typeNum){
        Page<article> pg = new Page<>(pageNum, 10);
        IPage<article> articleIPage = articleMapper.selectJoinPage(pg,article.class,
                new MPJLambdaWrapper<ArticleEntity>()
                        .selectAll(ArticleEntity.class)
                        .select(UserEntity::getUserName)
                        .select(UserEntity::getUserImg)
//                        .select(ArticleEntity::getArticleImg)
                        .eq(ArticleEntity::getType,typeNum)
                        .leftJoin(UserEntity.class,UserEntity::getUserId,ArticleEntity::getUserId)
                        .orderByDesc(ArticleEntity::getCreateTime));
//        System.out.println("articleIPage.getRecords()");
//        System.out.println(articleIPage.getRecords());
//        for (article article0 : articleIPage.getRecords()) {
//            if(article0.getArticleImg()==null){
//                continue;
//            }
//            System.out.println(article0);
//            System.out.println(article0.getArticleImg());
//            String[] parts = article0.getArticleImg().replaceAll("\\[|\\]", "").split(", ");
//            List<String> resultList = new ArrayList<>();
//            // 将分割后的字符串添加到列表
//            for (String part : parts) {
//                resultList.add(part);
//            }
//            String[] imgArray = article0.getArticleImg().replace("[", "").replace("]", "").split(",");
//            if (imgArray.length > 0) {
//                System.out.println("imgArray");
//                System.out.println(imgArray);
//                article0.setArticleImg(imgArray[0].replace("'", "").replace("'", ""));
//            }
//        }

        return articleIPage;

//        QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();
//        queryWrapper.select("*","`user`.user_name","`user`.user_img");
//        queryWrapper.last("LEFT JOIN\n" +
//                "    user ON article.user_id = user.user_id WHERE `type`="+Integer.toString(typeNum) + "\n ORDER BY create_time DESC");
//        //获取结果的第几页
//        Page<ArticleEntity> page = new Page<>(pageNum, 10);
//        Page<ArticleEntity> articlePage = articleMapper.selectPage(page,queryWrapper);
//        return articlePage;
    }
    public IPage<TrainArticleVo> loadTrian(int pageNum, int typeNum){
        Page<TrainArticleVo> pg = new Page<>(pageNum, 10);
        IPage<TrainArticleVo> articleIPage = articleMapper.selectJoinPage(pg, TrainArticleVo.class,
                new MPJLambdaWrapper<ArticleEntity>()
                        .select(ArticleEntity::getContent)
                        .select(ArticleEntity::getCreateTime)
                        .select(ArticleEntity::getArticleId)
                        .select(ArticleEntity::getLikeNum)
                        .select(ArticleEntity::getSaveNum)
                        .select(ArticleEntity::getViewNum)
                        .isNotNull(ArticleEntity::getRoomId)
                        .select(UserEntity::getUserName)
                        .select(UserEntity::getUserImg)
                        .selectAll(RoomEntity.class)
                        .eq(ArticleEntity::getType,typeNum)
                        .leftJoin(UserEntity.class,UserEntity::getUserId,ArticleEntity::getUserId)
                        .leftJoin(RoomEntity.class,RoomEntity::getRoomId,ArticleEntity::getRoomId)
                        .orderByDesc(ArticleEntity::getCreateTime));
//        articleIPage.getRecords().forEach(System.out::println);

        return articleIPage;
    }

    //发贴，内容插入帖子数据表
    public ArticleEntity publish_learn(PublishLearnArticleDo publishLearnArticleDo,UserEntity user) throws IOException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss ");
        String date = formatter.format(new Date(System.currentTimeMillis()));
        UpdateWrapper<UserEntity> wrapper = new UpdateWrapper();
        wrapper.eq("user_id",user.getUserId());
        wrapper.setSql("article_num = article_num + 1");
        userMapper.update(null,wrapper);
        ArticleEntity articleEntity =new ArticleEntity();
        articleEntity.setUserId(String.valueOf(user.getUserId()));
        articleEntity.setContent(publishLearnArticleDo.getContext());
        articleEntity.setTitle(publishLearnArticleDo.getTitle());
        articleEntity.setType(publishLearnArticleDo.getArctleType());
        articleEntity.setCreateTime(date);
//        articleEntity.setArticleImg(publishLearnArticleDo.getArticleImg().toString());
        articleEntity.setLikeNum("0");
        articleEntity.setSaveNum("0");
        articleEntity.setViewNum("0");
        articleMapper.insert(articleEntity);
        System.out.println("articleEntity");
        System.out.println(articleEntity);
        JSONObject res = new JSONObject();
        List<String> result = new ArrayList<>();
        System.out.println("publishLearnArticleDo.getArticleImg()");
        System.out.println(publishLearnArticleDo.getArticleImg());
        try {
            int num = 1;
            for(String base64String : publishLearnArticleDo.getArticleImg()){
                System.out.println("base64String");
                System.out.println(base64String);
                BufferedImage image = convert(base64String);

                BufferedImage compressedImage = compress(image); // Compress the image using your compress method
                String fileExtension = getImageFormat(base64String);
                String msg = minioUtils.uploadBufferedIllustrationImage(compressedImage, "illustration", articleEntity.getArticleId(), num++, fileExtension);
                result.add(msg);
            }
            if (user.getOpenId() != null && !user.getOpenId().equals("")){
                articleEntity.setImgNum(num - 1);
            } else {
                articleEntity.setImgNum(0);
            }
            // Upload the compressed image
        } catch (Exception e) {
            e.printStackTrace();
            res.put("code", 0);
            res.put("msg", "上传失败");
        }
        articleEntity.setArticleImg(result.toString());
        articleMapper.updateById(articleEntity);
        return articleEntity;
    }

    public void publish_train_content(PublishLearnArticleDo publishLearnArticleDo,String userId,String roomId)  {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss ");
        String date = formatter.format(new Date(System.currentTimeMillis()));
        UpdateWrapper<UserEntity> wrapper = new UpdateWrapper();
        wrapper.eq("user_id",userId);
        wrapper.setSql("article_num = article_num + 1");
        userMapper.update(null,wrapper);
        ArticleEntity articleEntity =new ArticleEntity();
        articleEntity.setUserId(userId);
        articleEntity.setContent(publishLearnArticleDo.getContext());
        articleEntity.setTitle(publishLearnArticleDo.getTitle());
        articleEntity.setType(publishLearnArticleDo.getArctleType());
        articleEntity.setCreateTime(date);
        articleEntity.setLikeNum("0");
        articleEntity.setSaveNum("0");
        articleEntity.setViewNum("0");
        articleEntity.setRoomId(roomId);
        articleMapper.insert(articleEntity);
    }

    //训练贴
    public int publish_train(PublishTrainArticleDo publishTrainArticleDo,String userId) throws ParseException {
        RoomEntity roomEntity = new RoomEntity();
        //插入数据
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = formatter.format(new Date(System.currentTimeMillis()));
        roomEntity.setArea(publishTrainArticleDo.getArea());
        roomEntity.setRoomName(publishTrainArticleDo.getRoomName());
        roomEntity.setRoomState(-1);
        roomEntity.setType(publishTrainArticleDo.getRoomType());
        roomEntity.setRealNumber(0);
        roomEntity.setPreference(publishTrainArticleDo.getPreference());
        System.out.println("publishTrainArticleDo.getNumber()");
        System.out.println(publishTrainArticleDo.getNumber());
        roomEntity.setMaxNumber(Integer.valueOf(publishTrainArticleDo.getNumber()));

        roomEntity.setStartTime(formatter.parse(publishTrainArticleDo.getStartTime()));
        roomEntity.setIsMatch(publishTrainArticleDo.getIsMatch());
        roomEntity.setUserId(Integer.parseInt(userId));
        reserveRoomMapper.insert(roomEntity);
        return roomEntity.getRoomId();
    }
    public IPage<article> search(Integer pageNum, Integer typeNum,String keyword){
        //寻找文章表标题里面是否存在关键词
        Page<article> pg = new Page<>(pageNum, 10);
        IPage<article> articleIPage = articleMapper.selectJoinPage(pg,article.class,
                new MPJLambdaWrapper<ArticleEntity>()
                        .selectAll(ArticleEntity.class)
                        .select(UserEntity::getUserName)
                        .select(UserEntity::getUserImg)
                        .eq(ArticleEntity::getType,typeNum)
                        .like(ArticleEntity::getTitle,keyword)
                        .leftJoin(UserEntity.class,UserEntity::getUserId,ArticleEntity::getUserId)
                        .leftJoin(LikeEntity.class,LikeEntity::getArticle_id,ArticleEntity::getArticleId)
                        .orderByDesc(ArticleEntity::getCreateTime));
        QueryWrapper<LikeEntity> queryWrapper0 = new QueryWrapper<>();
        QueryWrapper<SaveEntity> queryWrapper1 = new QueryWrapper<>();
        for (article article0 : articleIPage.getRecords()) {
            queryWrapper0.clear();
            queryWrapper0.eq("article_id",article0.getArticleId());
            queryWrapper0.eq("user_id",article0.getUserId());
            queryWrapper1.clear();
            queryWrapper1.eq("article_id",article0.getArticleId());
            queryWrapper1.eq("user_id",article0.getUserId());

            article0.setLike(likeMapper.selectCount(queryWrapper0));
            article0.setSave(saveMapper.selectCount(queryWrapper1));
        }
        return articleIPage;
//        QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();
//        queryWrapper.select("*","user_name","user_img");
//        String sql_str = String.format("LEFT JOIN\n" +
//                "user ON article.user_id = user.user_id WHERE article.title LIKE %s AND article.type =%s " +
//                "\n ORDER BY create_time DESC","\'%"+keyword+"%\'",Integer.toString(typeNum));
//        queryWrapper.last(sql_str);
//        Page<ArticleEntity> page = new Page<>(pageNum, 10);
//        Page<ArticleEntity> articlePage = articleMapper.selectPage(page,queryWrapper);
//        return articlePage;
    }
    public  IPage<TrainArticleVo> searchTrain(Integer page, Integer type,String keyword){
        Page<TrainArticleVo> pg = new Page<>(page, 10);
        IPage<TrainArticleVo> articleIPage = articleMapper.selectJoinPage(pg, TrainArticleVo.class,
                new MPJLambdaWrapper<ArticleEntity>()
                        .select(ArticleEntity::getContent)
                        .select(ArticleEntity::getArticleId)
                        .select(ArticleEntity::getLikeNum)
                        .select(ArticleEntity::getSaveNum)
                        .select(ArticleEntity::getViewNum)
                        .isNotNull(ArticleEntity::getRoomId)
                        .select(UserEntity::getUserName)
                        .select(UserEntity::getUserImg)
                        .selectAll(RoomEntity.class)
                        .like(ArticleEntity::getTitle,keyword)
                        .eq(ArticleEntity::getType,type)
                        .leftJoin(UserEntity.class,UserEntity::getUserId,ArticleEntity::getUserId)
                        .leftJoin(RoomEntity.class,RoomEntity::getRoomId,ArticleEntity::getRoomId)
                        .orderByDesc(ArticleEntity::getCreateTime));
        QueryWrapper<LikeEntity> queryWrapper0 = new QueryWrapper<>();
        QueryWrapper<SaveEntity> queryWrapper1 = new QueryWrapper<>();
        for (TrainArticleVo article0 : articleIPage.getRecords()) {
            queryWrapper0.clear();
            queryWrapper0.eq("article_id",article0.getArticleId());
            queryWrapper0.eq("user_id",article0.getUserId());
            queryWrapper1.clear();
            queryWrapper1.eq("article_id",article0.getArticleId());
            queryWrapper1.eq("user_id",article0.getUserId());
            article0.setLike(likeMapper.selectCount(queryWrapper0));
            article0.setSave(saveMapper.selectCount(queryWrapper1));
        }
        return articleIPage;
    }
}
